/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.product.rest;


import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.constant.ShopConstants;
import co.yixiang.logging.aop.log.AppLog;
import co.yixiang.common.aop.NoRepeatSubmit;
import co.yixiang.common.bean.LocalUser;
import co.yixiang.common.interceptor.AuthCheck;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.enums.AppFromEnum;
import co.yixiang.enums.ProductEnum;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.modules.mp.config.WxMaConfiguration;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.product.domain.YxCommissionDetail;
import co.yixiang.modules.product.domain.YxStoreProduct;
import co.yixiang.modules.product.domain.YxStoreProductRelation;
import co.yixiang.modules.product.param.YxStoreProductQueryParam;
import co.yixiang.modules.product.param.YxStoreProductRelationQueryParam;
import co.yixiang.modules.product.service.YxCommissionDetailService;
import co.yixiang.modules.product.service.YxStoreProductRelationService;
import co.yixiang.modules.product.service.YxStoreProductReplyService;
import co.yixiang.modules.product.service.YxStoreProductService;
import co.yixiang.modules.product.vo.ProductVo;
import co.yixiang.modules.product.vo.ReplyCountVo;
import co.yixiang.modules.product.vo.YxStoreProductQueryVo;
import co.yixiang.modules.product.vo.YxStoreProductReplyQueryVo;
import co.yixiang.modules.services.CreatShareProductService;
import co.yixiang.modules.shop.domain.YxSystemAttachment;
import co.yixiang.modules.shop.domain.YxSystemUserLevel;
import co.yixiang.modules.shop.service.YxSystemAttachmentService;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.YxSystemUserLevelService;
import co.yixiang.modules.user.service.YxUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.FontFormatException;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 商品控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-19
 */
@Slf4j
@RestController
@Api(value = "产品模块", tags = "商城:产品模块", description = "产品模块")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StoreProductController {

    private final YxStoreProductService storeProductService;
    private final YxStoreProductRelationService productRelationService;
    private final YxStoreProductReplyService replyService;
    private final YxSystemConfigService systemConfigService;
    private final YxSystemAttachmentService systemAttachmentService;
    private final CreatShareProductService creatShareProductService;
    private final YxStoreOrderCartInfoService orderCartInfoService;
    private final YxUserService yxUserService;
    private final YxCommissionDetailService yxCommissionDetailService;
    private final YxSystemUserLevelService yxSystemUserLevelService;
    @Value("${file.path}")
    private String path;


    /**
     * 获取首页更多产品
     */
    @GetMapping("/groom/list/{type}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型：1精品推荐，2热门榜单，3首发新品，4促销单品", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "获取首页更多产品",notes = "获取首页更多产品")
    public ApiResult<Map<String,Object>> moreGoodsList(@PathVariable Integer type){
        Map<String,Object> map = new LinkedHashMap<>();
        if(ProductEnum.TYPE_1.getValue().equals(type)){// 精品推荐
            map.put("list",storeProductService.getList(1,20,ProductEnum.TYPE_1.getValue()));
        }else if(type.equals(ProductEnum.TYPE_2.getValue())){// 热门榜单
            map.put("list",storeProductService.getList(1,20,ProductEnum.TYPE_2.getValue()));
        }else if(type.equals(ProductEnum.TYPE_3.getValue())){// 首发新品
            map.put("list",storeProductService.getList(1,20,ProductEnum.TYPE_3.getValue()));
        }else if(type.equals(ProductEnum.TYPE_4.getValue())){// 促销单品
            map.put("list",storeProductService.getList(1,20,ProductEnum.TYPE_4.getValue()));
        }

        return ApiResult.ok(map);
    }

    /**
     * 获取产品列表
     */
    @GetMapping("/products")
    @ApiOperation(value = "商品列表",notes = "商品列表")
    public ApiResult<List<YxStoreProductQueryVo>> goodsList(YxStoreProductQueryParam productQueryParam){
        if(ObjectUtil.isNotNull(LocalUser.getUser())){
            long uid = LocalUser.getUser().getUid();
            //添加足迹
            YxStoreProductRelation storeProductRelation = new YxStoreProductRelation();
            storeProductRelation.setProductId(new Long(1));
            storeProductRelation.setUid(uid);
            if("25".equals(productQueryParam.getSid())){
                storeProductRelation.setCategory("线下物料");
            }else{
                storeProductRelation.setCategory("商品列表");
            }
            storeProductRelation.setCreateTime(new Date());
            storeProductRelation.setType("foot");
            productRelationService.save(storeProductRelation);
        }
        //long uid = LocalUser.getUser().getUid();
        /*//添加足迹
        YxStoreProductRelation storeProductRelation = new YxStoreProductRelation();
        storeProductRelation.setProductId(new Long(1));
        storeProductRelation.setUid(uid);
        if("25".equals(productQueryParam.getSid())){
            storeProductRelation.setCategory("线下物料");
        }else{
            storeProductRelation.setCategory("商品列表");
        }
        storeProductRelation.setCreateTime(new Date());
        storeProductRelation.setType("foot");
        productRelationService.save(storeProductRelation);*/
        return ApiResult.ok(storeProductService.getGoodsList(productQueryParam));
    }

    /**
     * 为你推荐
     */
    @GetMapping("/product/hot")
    @ApiOperation(value = "为你推荐",notes = "为你推荐")
    public ApiResult<List<YxStoreProductQueryVo>> productRecommend(YxStoreProductQueryParam queryParam){
        return ApiResult.ok(storeProductService.getList(queryParam.getPage(), queryParam.getLimit(),
                ShopCommonEnum.IS_STATUS_1.getValue()));
    }

    /**
     * 商品详情海报
     */
    @AppLog(value = "商品详情海报", type = 1)
    @AuthCheck
    @GetMapping("/product/poster/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "商品详情海报",notes = "商品详情海报")
    public ApiResult<String> prodoctPoster(@PathVariable Integer id,@RequestParam(value = "from",defaultValue = "h5") String from) throws IOException, FontFormatException {
        YxUser userInfo = LocalUser.getUser();

        long uid = userInfo.getUid();

        YxStoreProduct storeProduct = storeProductService.getById(id);
        // 海报
        String siteUrl = systemConfigService.getData(SystemConfigConstants.SITE_URL);
        if(StrUtil.isEmpty(siteUrl)){
            return ApiResult.fail("未配置h5地址");
        }
        String apiUrl = systemConfigService.getData(SystemConfigConstants.API_URL);
        if(StrUtil.isEmpty(apiUrl)){
            return ApiResult.fail("未配置api地址");
        }
        String name = id+"_"+uid + "_"+from+"_product_detail_wap.jpg";
        YxSystemAttachment attachment = systemAttachmentService.getInfo(name);
        String sepa = File.separator;
        String fileDir = path+"qrcode"+ sepa;
        String qrcodeUrl = "";
        String str ="id="+id+"-spread="+uid+"-pageType=good";
        if(ObjectUtil.isNull(attachment)){
            File file = FileUtil.mkdir(new File(fileDir));
            //如果类型是小程序
            if(AppFromEnum.ROUNTINE.getValue().equals(from)){
                //siteUrl = siteUrl+"/product/";
                //生成二维码
                /*QrCodeUtil.generate(siteUrl+"?id="+id+"&spread="+uid+"&pageType=good&codeType="+AppFromEnum.ROUNTINE.getValue(), 180, 180,
                        FileUtil.file(fileDir+name));*/
                //生成小程序码
                getminiqrQr(str,fileDir,name);
            }
            else if(AppFromEnum.APP.getValue().equals(from)){
                siteUrl = siteUrl+"/product/";
                //生成二维码
                QrCodeUtil.generate(siteUrl+"?id="+id+"&spread="+uid+"&pageType=good&codeType="+AppFromEnum.APP.getValue(), 180, 180,
                        FileUtil.file(fileDir+name));
            }else if(AppFromEnum.H5.getValue().equals(from)){//如果类型是h5
                //生成二维码
                QrCodeUtil.generate(siteUrl+"/detail/"+id+"?spread="+uid, 180, 180,
                        FileUtil.file(fileDir+name));
            }else {
                //生成二维码
                String uniUrl = systemConfigService.getData(SystemConfigConstants.UNI_SITE_URL);
                siteUrl =  StrUtil.isNotBlank(uniUrl) ? uniUrl :  ShopConstants.DEFAULT_UNI_H5_URL;
                QrCodeUtil.generate(siteUrl+"/pages/shop/GoodsCon/index?id="+id+"&spread="+uid, 180, 180,
                        FileUtil.file(fileDir+name));
            }
            systemAttachmentService.newAttachment4SpreadAdd(name,String.valueOf(FileUtil.size(file)),
                    fileDir+name,"qrcode/"+name,uid,"","1",storeProduct.getId());

            qrcodeUrl = apiUrl + "/api/file/qrcode/"+name;
        }else{
            qrcodeUrl = apiUrl + "/api/file/" + attachment.getSattDir();
        }
        String spreadPicName = id+"_"+uid + "_"+from+"_product_user_spread.jpg";
        String spreadPicPath = fileDir+spreadPicName;
        String rr =  creatShareProductService.creatProductPic(storeProduct,qrcodeUrl,
                spreadPicName,spreadPicPath,apiUrl,userInfo);
        return ApiResult.ok(rr);
    }



    /**
     * 普通商品详情
     */
    @AppLog(value = "普通商品详情", type = 1)
    @AuthCheck
    @GetMapping("/product/detail/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", paramType = "query", dataType = "long",required = true),
            @ApiImplicitParam(name = "latitude", value = "纬度", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "longitude", value = "经度", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "from", value = "来自:", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "普通商品详情",notes = "普通商品详情")
    public ApiResult<Map<String,Object>> detail(@PathVariable long id,
                                       @RequestParam(value = "",required=false) String latitude,
                                       @RequestParam(value = "",required=false) String longitude,
                                       @RequestParam(value = "",required=false) String from)  {
        long uid = LocalUser.getUser().getUid();
        storeProductService.incBrowseNum(id);
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM");
        String month =fm.format(new Date());
        String count =orderCartInfoService.getOrderCountByFree4pay(uid,id,month);
        Map<String,Object> map = Maps.newHashMap();
        ProductVo productDTO = storeProductService.goodsDetail(id,uid,latitude,longitude);
        Integer frequency =productDTO.getStoreInfo().getFrequency();
        Integer derivableCount =frequency-Integer.parseInt(count);
        String is_buy ="N";
        if(frequency>Integer.parseInt(count)){
            is_buy ="Y";
        }
        Integer nextLevel =0;
        YxUser user = yxUserService.getById(uid);
        if(user.getLevel() ==0){
            nextLevel =user.getLevel()+1;
            YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                    .eq(YxSystemUserLevel::getGrade,nextLevel));
            map.put("nextLevel",nextLevel);
            map.put("nextLevelName",yxSystemUserLevel.getName());
            map.put("commissionSum",0);
        }else if(user.getLevel() ==1){
            nextLevel =user.getLevel()+1;
            YxCommissionDetail yxCommissionDetail=yxCommissionDetailService.getOne(new LambdaQueryWrapper<YxCommissionDetail>()
                    .eq(YxCommissionDetail ::getCommissionTypeId,productDTO.getStoreInfo().getCommissionTypeId())
                    .eq(YxCommissionDetail ::getLevel,nextLevel));
            if(ObjectUtil.isNotNull(yxCommissionDetail)){
                map.put("commissionSum",yxCommissionDetail.getGoodsValue());
                YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                        .eq(YxSystemUserLevel::getGrade,nextLevel));
                map.put("nextLevel",nextLevel);
                map.put("nextLevelName",yxSystemUserLevel.getName());
            }
        }else {
            nextLevel =user.getLevel();
            //map.put("nextLevel",nextLevel);
            YxCommissionDetail yxCommissionDetail=yxCommissionDetailService.getOne(new LambdaQueryWrapper<YxCommissionDetail>()
                    .eq(YxCommissionDetail ::getCommissionTypeId,productDTO.getStoreInfo().getCommissionTypeId())
                    .eq(YxCommissionDetail ::getLevel,nextLevel));
            if(ObjectUtil.isNotNull(yxCommissionDetail)){
                BigDecimal goodsValue =new BigDecimal(yxCommissionDetail.getGoodsValue());

                YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.getOne(new LambdaQueryWrapper<YxSystemUserLevel>()
                        .eq(YxSystemUserLevel::getGrade,nextLevel));
                if(yxSystemUserLevel.getCommissionSum().compareTo(new BigDecimal("0"))==1){
                    JSONObject jsonObj = yxUserService.getParentByUserid(user.getUid(),nextLevel);
                    //JSONObject jsonObj = userMgr.getParentByUserid(mainUserId,main_member_level);
                    System.out.println("11111111111111");
                    String parent_id = jsonObj.getString("parent_id");
                    String member_id = jsonObj.getString("member_id");
                    log.info("parent_id用户：" + parent_id+"-------------member_id"+member_id);
                    /*if(!isEmpty(parent_id)){
                        if(user.getSpreadUid().intValue() !=0){
                            YxUser parentUser =yxUserService.getById(user.getSpreadUid());
                            if(parentUser.getLevel() <=Integer.parseInt(member_id)){
                                BigDecimal pjSum =yxSystemUserLevel.getCommissionSum().multiply(new BigDecimal(productDTO.getStoreInfo().getLevelAmount()));
                                goodsValue =goodsValue.subtract(pjSum);
                            }
                        }
                        log.info( "上级parentUser id+等级"+parent_id+"-----"+Integer.parseInt(member_id));
                    }*/
                }
                map.put("commissionSum",goodsValue);
                map.put("nextLevel",nextLevel);
                map.put("nextLevelName",yxSystemUserLevel.getName());
            }
        }
        map.put("productDTO",productDTO);
        map.put("is_buy",is_buy);
        map.put("derivableCount",derivableCount);//当月剩余购买次数
        return ApiResult.ok(map);
    }

    /**
     * 添加收藏
     */
    @AppLog(value = "添加收藏", type = 1)
    @NoRepeatSubmit
    @AuthCheck
    @PostMapping("/collect/add")
    @ApiOperation(value = "添加收藏",notes = "添加收藏")
    public ApiResult<Boolean> collectAdd(@Validated @RequestBody YxStoreProductRelationQueryParam param){
        long uid = LocalUser.getUser().getUid();
        if(!NumberUtil.isNumber(param.getId())) {
            throw new YshopException("参数非法");
        }
        productRelationService.addRroductRelation(Long.valueOf(param.getId()),uid,param.getCategory());
        return ApiResult.ok();
    }

    /**
     * 取消收藏
     */
    @AppLog(value = "取消收藏", type = 1)
    @NoRepeatSubmit
    @AuthCheck
    @PostMapping("/collect/del")
    @ApiOperation(value = "取消收藏",notes = "取消收藏")
    public ApiResult<Boolean> collectDel(@Validated @RequestBody YxStoreProductRelationQueryParam param){
        long uid = LocalUser.getUser().getUid();
        if(!NumberUtil.isNumber(param.getId())) {
            throw new YshopException("参数非法");
        }
        productRelationService.delRroductRelation(Long.valueOf(param.getId()),
                uid,param.getCategory());
        return ApiResult.ok();
    }

    /**
     * 获取产品评论
     */
    @GetMapping("/reply/list/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", paramType = "query", dataType = "long",required = true),
            @ApiImplicitParam(name = "type", value = "评论分数类型", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page", value = "页码,默认为1", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "页大小,默认为10", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "获取产品评论",notes = "获取产品评论")
    public ApiResult<List<YxStoreProductReplyQueryVo>> replyList(@PathVariable Long id,
                                                                 @RequestParam(value = "type",defaultValue = "0") int type,
                                                                 @RequestParam(value = "page",defaultValue = "1") int page,
                                                                 @RequestParam(value = "limit",defaultValue = "10") int limit){
        return ApiResult.ok(replyService.getReplyList(id,type, page,limit));
    }

    /**
     * 获取产品评论数据
     */
    @GetMapping("/reply/config/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", paramType = "query", dataType = "int")
    })
    @ApiOperation(value = "获取产品评论数据",notes = "获取产品评论数据")
    public ApiResult<ReplyCountVo> replyCount(@PathVariable Integer id){
        return ApiResult.ok(replyService.getReplyCount(id));
    }

    public void getminiqrQr(String sceneStr,String path,String name) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
            File file = new File(path+name);
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            WxMaCodeLineColor line_color = new WxMaCodeLineColor("0","0","0");
            byte[] qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(sceneStr, "pages/shop/GoodsCon/index", 130, false, line_color, true);
            inputStream = new ByteArrayInputStream(qrCodeBytes);
            int len = 0;
            while ((len = inputStream.read(qrCodeBytes, 0, 1024)) != -1) {
                outputStream.write(qrCodeBytes, 0, len);
            }
            outputStream.flush();
        } catch (Exception ex) {
            log.info("生成小程序码失败，message:{}", ex.getMessage());
        } finally {
            try {
                outputStream.close();
            } catch (Exception ex) {
                log.error("关闭IO流失败,msg:{}", ex.getMessage());
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 为你推荐
     */
    @GetMapping("/product/getDealPic")
    @ApiOperation(value = "获取协议图片",notes = "获取协议图片")
    public ApiResult<Object> getDealPic(){
        Map<String,Object> map = Maps.newHashMap();
        String dealImage =systemConfigService.getData(ShopConstants.DEAL_IMAGE);
        map.put("dealImage",dealImage);
        return ApiResult.ok(map);
    }

    public static boolean isEmpty(Object obj) {
        if (obj instanceof String) {
            String s = (String) obj;
            if ((s == null) || s.trim().length() == 0) {
                return true;
            }
        } else if (obj instanceof Collection) {
            if (obj == null || ((Collection) obj).size() == 0)
                return true;
        } else if (obj instanceof Map) {
            if (obj == null || ((Map) obj).size() == 0)
                return true;
        } else if (obj == null) {
            return true;
        }
        return false;
    }

}

